package com.robot.member.controller;

import com.robot.member.client.AgentClient;
import com.robot.member.client.SmsClient;
import com.robot.member.pojo.AgentApply;
import com.robot.member.pojo.Member;
import com.robot.member.service.AgentApplyService;
import com.robot.member.service.MemberService;
import entity.*;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import util.CheckUtil;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 代理商入驻申请agent_apply控制器层
 *
 * @author wuyunbin
 */
@RestController
@CrossOrigin
@RequestMapping("/agent_apply")
public class AgentApplyController {
    @Autowired
    private AgentApplyService applyService;
    @Autowired
    private MemberService memberService;

    @Autowired
    private AgentClient agentClient;
    @Autowired
    private SmsClient smsClient;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private CheckUtil checkUtil;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "application/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map<String, String> searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        logger.info("searchMap=" + searchMap);
        searchMap.put("memberId", claims.getId());
        Page<AgentApply> pageList = applyService.findSearch(searchMap, page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<AgentApply>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(StatusCode.SUCCESS_QUERY, applyService.findSearch(searchMap));
    }

    /**
     * 查看代理申请
     *
     * @return
     */
    @GetMapping("application/{id}")
    public Result application(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        AgentApply agentApplyInDb = applyService.findByIdAndMemberIdAndDeletedAtIsNull(id, claims.getId());
        logger.info("agentApplyInDb=" + agentApplyInDb);
        String message = applyService.checkPojo(agentApplyInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        return new Result(StatusCode.SUCCESS_QUERY, agentApplyInDb);
    }

    /**
     * 代理申请
     *
     * @param apply
     */
    @PostMapping("{checkCode}")
    public Result add(@RequestBody AgentApply apply, @PathVariable String checkCode) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        //判断手机号
        String phone = apply.getPhone();
        Status status = applyService.checkPhoneUsed(apply.getPhone(), claims.getId());
        if (status != null) {
            return new Result(status);
        }

        checkCode = checkCode.trim();
        if ("".equals(checkCode)) {
            return new Result(StatusCode.ERROR_VERIFICATION_CODE);
        }
        //验证码是不是过期
        Sms sms = new Sms("member", phone, "agentApply");
        String scene = "agentApply";
        if (!smsClient.isCheckCodeExpire(sms)) {
            return new Result(StatusCode.ERROR_VERIFICATION_CODE_EXPIRED);
        }
        //验证码是否正确
        if (!smsClient.isCorrectCheckCode(sms, checkCode)) {
            return new Result(StatusCode.ERROR_VERIFICATION_CODE);
        }

        Member memberInDb = memberService.findById(claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        if (apply.getContact() == null || "".equals(apply.getContact())) {
            return new Result(StatusCode.ERROR_CONTACT_REQUIRED);
        }
        if (apply.getProvinceId() == null || "".equals(apply.getProvinceId()) || apply.getProvince() == null || "".equals(apply.getProvince())) {
            return new Result(StatusCode.ERROR_PROVINCE_REQUIRED);
        }
        if (apply.getCityId() == null || "".equals(apply.getCityId()) || apply.getCity() == null || "".equals(apply.getCity())) {
            return new Result(StatusCode.ERROR_CITY_REQUIRED);
        }
        if (apply.getAreaId() == null || "".equals(apply.getAreaId()) || apply.getArea() == null || "".equals(apply.getArea())) {
            return new Result(StatusCode.ERROR_AREA_REQUIRED);
        }
        apply.setMemberId(memberInDb.getId());
        apply.setAvatar(memberInDb.getAvatar() == null ? "" : memberInDb.getAvatar());
        apply.setNickname(memberInDb.getNickname());
        applyService.add(apply);
        smsClient.deleteCheckCode(sms);
        return new Result(StatusCode.SUCCESS_APPLY);
    }

    /**
     * 代理申请审核失败后修改信息
     *
     * @param id
     * @param apply
     * @return
     */
    @RequestMapping(value = "firstTrial/{id}",method = RequestMethod.PUT)
    @Transactional(rollbackFor = Exception.class)
    public Result firstTrial(@PathVariable String id, @RequestBody AgentApply apply) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        logger.info("apply=" + apply);
        AgentApply agentApplyInDb = applyService.findByIdAndMemberIdAndDeletedAtIsNull(id, claims.getId());
        logger.info("agentApplyInDb=" + agentApplyInDb);
        String message = applyService.checkPojo(agentApplyInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }
        String agentApplyStatusSuccess = "1";
        if (agentApplyStatusSuccess.equals(agentApplyInDb.getStatus())) {
            return new Result(StatusCode.ERROR, "该代理申请已审核通过");
        }
        //判断手机号
        if (apply.getPhone() != null && !"".equals(apply.getPhone()) && !agentApplyInDb.getPhone().equals(apply.getPhone())) {
            Status status = applyService.checkPhoneUsed(apply.getPhone(), claims.getId());
            if (status != null) {
                return new Result(status);
            }
            agentApplyInDb.setPhone(apply.getPhone());
        }
        if (apply.getContact() != null && !"".equals(apply.getContact())) {
            agentApplyInDb.setContact(apply.getContact());
        }
        if (apply.getProvinceId() != null && !"".equals(apply.getProvinceId())) {
            agentApplyInDb.setProvinceId(apply.getProvinceId());
        }
        if (apply.getProvince() != null && !"".equals(apply.getProvince())) {
            agentApplyInDb.setProvince(apply.getProvince());
        }
        if (apply.getCityId() != null && !"".equals(apply.getCityId())) {
            agentApplyInDb.setCityId(apply.getCityId());
        }
        if (apply.getCity() != null && !"".equals(apply.getCity())) {
            agentApplyInDb.setCity(apply.getCity());
        }
        if (apply.getAreaId() != null && !"".equals(apply.getAreaId())) {
            agentApplyInDb.setAreaId(apply.getAreaId());
        }
        if (apply.getArea() != null && !"".equals(apply.getArea())) {
            agentApplyInDb.setArea(apply.getArea());
        }

        applyService.update(agentApplyInDb);
        return new Result(StatusCode.SUCCESS_APPLY);
    }

    /**
     * 软删除代理申请单
     *
     * @param id
     */
    @RequestMapping(value = "deleteById/{id}", method = RequestMethod.PUT)
    public Result deleteById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        AgentApply agentApplyInDb = applyService.findByIdAndMemberIdAndDeletedAtIsNull(id, claims.getId());
        logger.info("agentApplyInDb=" + agentApplyInDb);
        String message = applyService.checkPojo(agentApplyInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        agentApplyInDb.setDeletedAt(LocalDateTime.now());
        applyService.update(agentApplyInDb);
        return new Result(StatusCode.SUCCESS_DELETED);
    }

    /**
     * 强删除代理申请单
     *
     * @param id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        applyService.deleteById(id);
        return new Result(StatusCode.SUCCESS_DELETED);
    }
}